package com.lzj.demo.jdbc;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class BrandQuery {
    @Test
    public void test() throws Exception {
        //获取定义在src/main/resources文件夹中的配置文件
        ClassPathResource resource = new ClassPathResource("druid.properties");
        //加载配置文件
        Properties prop = new Properties();
        prop.load(resource.getStream());
        //获取连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
        //获取数据库连接 Connection
        Connection conn = dataSource.getConnection();

        //定义SQL
        String sql = "select * from tb_brand;";
        //获取PreparedStatement对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        //设置参数 执行SQL
        ResultSet rs = preparedStatement.executeQuery();

        //装载brand对象
        List<Brand> list = new ArrayList<>();

        //遍历结果集
        while (rs.next()) {
            //获取数据
            int id = rs.getInt("id");
            String brandName = rs.getString("brand_name");
            String companyName = rs.getString("company_name");
            int ordered = rs.getInt("ordered");
            String description = rs.getString("description");
            int status = rs.getInt("status");

            //定义Brand对象接收查询结果
            Brand brand = new Brand();
            brand.setId(id);
            brand.setBrandName(brandName);
            brand.setCompanyName(companyName);
            brand.setOrdered(ordered);
            brand.setDescription(description);
            brand.setStatus(status);

            //把brand对象放进list集合
            list.add(brand);
        }

        //在控制台打印结果
        System.out.println("查询结果集:"+list);

        //释放资源
        rs.close();
        preparedStatement.close();
        conn.close();
    }
}
